//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.comprosoft.telnet.server;

import com.comprosoft.telnet.command.CustomProcess;
import com.comprosoft.telnet.configuration.ServerProperties;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TelnetServer {
    private final Logger logger = Logger.getLogger("TelnetServer");
    private ServerSocket server = null;
    private final ExecutorService executor;
    private final String workingDir;
    private final int GIVEN_PORT;
    private Map<Long, CustomProcess> longCustomProcessMap;

    public TelnetServer(String port) {
        this.executor = Executors.newFixedThreadPool(Integer.valueOf(ServerProperties.MAX_THREADS.getValue()));
        this.workingDir = System.getProperty("user.dir");
        this.longCustomProcessMap = new HashMap();
        this.GIVEN_PORT = port != null ? Integer.valueOf(port) : 0;
    }

    public Map<Long, CustomProcess> getLongCustomProcessMap() {
        return this.longCustomProcessMap;
    }

    public void run() {
        try {
            this.server = new ServerSocket(this.GIVEN_PORT == 0 ? Integer.parseInt(ServerProperties.PORT_NUMBER.getValue()) : this.GIVEN_PORT);
            this.logger.info("Server running and listening on port : " + (this.GIVEN_PORT == 0 ? Integer.parseInt(ServerProperties.PORT_NUMBER.getValue()) : this.GIVEN_PORT));

            while(true) {
                Socket s = this.server.accept();
                this.logger.info("Connection to IP: " + s.getInetAddress().toString());
                this.executor.execute(new ClientWorker(s, this.workingDir, this));
            }
        } catch (BindException var6) {
            this.logger.log(Level.SEVERE, var6.getMessage());
        } catch (IOException var7) {
            var7.printStackTrace();
            this.logger.log(Level.WARNING, "Another server is already running. Shutting down the server..");
        } finally {
            this.executor.shutdown();
        }

    }

    public boolean isRunning() {
        return !this.server.isClosed();
    }

    public void shutDown() throws IOException {
        if (this.server != null) {
            this.server.close();
        }

    }
}
